define([
    "dojo/_base/declare",
    "gistech/widgets/normalDialog/NormalDialog",
    "gistech/widgets/dialog/Dialog",
    "dojo/text!./templates/Template.html",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/dom-construct",
    "dojo/on","dojo/topic",
    "dojo/_base/connect",
    "gistech/util/ajaxUtil",
    "esri/tasks/query",
    "esri/tasks/QueryTask",
    "esri/graphic",
    "esri/geometry/geometryEngine",
    "esri/geometry/geodesicUtils",
    "esri/geometry/Polyline",
    "esri/toolbars/edit",
    "dojo/_base/event",
    "esri/geometry/webMercatorUtils",
    "esri/tasks/GeometryService",
    "esri/layers/FeatureLayer","esri/InfoTemplate",
    "esri/symbols/SimpleMarkerSymbol",
    "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleFillSymbol",
    "esri/renderers/UniqueValueRenderer", "esri/Color",
    "dojo/dom-style","dojo/query","dojo/dom-class"],
    function(declare,NormalDialog,Dialog,template,lang,style,domConstruct,
    		on,topic,eventconnect,ajaxUtil,Tquery,QueryTask,Graphic,geometryEngine,geodesicUtils,Polyline,Edit,event,webMercatorUtils,GeometryService,FeatureLayer,
    		InfoTemplate,SimpleMarkerSymbol,SimpleLineSymbol,SimpleFillSymbol,UniqueValueRenderer,Color,
    		domStyle,query,domClass){
        return declare([NormalDialog],{
            templateString:template,
            projectType:"洽谈项目", 
            LandFeatureLayer:null,//拓展图层
            handles:[],
            editing:false,
            landGraphic:null,
            graphiclayerArray:null,//要进行相交判断的图层
            landinfoTemplate:null,
            allowEditGeometry:false,
            editToolbar:null,
            geometryService:null,
            constructor:function (args) {
            	this.inherited(arguments);
            	this.map = args.map;
            	this.landgeo = args.landgeo;
                this.LandFeatureLayer=null;
            },
            postCreate:function(){
            	console.log("post")
                this.inherited(arguments);
                on(this.save, "click",lang.hitch(this,this.saveLandGeometryToDB));
                on(this.cancle,"click",lang.hitch(this,this.closeDialog));
            },
            startup:function(){
            	console.log("star")
                this.inherited(arguments);    
                this.setLandGeometry(this.landgeo);
                this.getThisLayer();
                this.changeProhectTypeAfterBind(this.landgeo);
                this.init();
                this.addEvents();
                this.updateGraphicLayerArray();
                
            },
            init:function(){
            	console.log("init")
            	this.bindArgs(this.landgeo);
            	this.editToolbar = new Edit(this.map);
            	 dojo.query("#XH")[0].value = "L"+getDateStr();
            	 dojo.query("#REGISTERDATE")[0].value = reduceformatDate(0,"-");
            	 var projecttype = dojo.query(".projecttype input");
                 for(var i=0;i<projecttype.length;i++){
     				on(projecttype[i], "click",lang.hitch(this,this.changeProjectTypeHandler));
     			}
                 this.handles=[on(this.geoedit,"click",lang.hitch(this,this.geoEdit))];
            },
            updateGraphicLayerArray:function(){
            	try{
            		this.graphiclayerArray=this.map.graphicsLayerIds;
            	}catch(e){}finally{}
            },
            addEvents:function(){
            	on(this.map,"click",lang.hitch(this,this.DeactiveEditbar));
            	on(this.editToolbar,"deactivate",lang.hitch(this,this.setLandGeometry));
            	on(this.LandFeatureLayer,"before-apply-edits",lang.hitch(this,function(){
            		try{debugger;this.map.graphics.clear();}finally{return ;}}))
            },
            setLandGeometry:function(graphic){
            	debugger
            	if(graphic.tool){
            		graphic=graphic.graphic
            	}
            	var geo = webMercatorUtils.webMercatorToGeographic(graphic.geometry);
            	var area=Math.abs(geodesicUtils.geodesicAreas([geo], esri.Units.SQUARE_METERS));
    			dojo.byId("TOTALAREA").value = area.toFixed(3);
    			dojo.byId("NETLANDAREA").value = area.toFixed(3);
            },
            //相交检查，暂时不用了
            checkEdit:function(evt){   
            	debugger
            	if(!evt){return ;}
            	this.updateGraphicLayerArray();
            	//目前地图上叠加的所有graphicsLayer 的id
            	 var graphiclayersArray=this.graphiclayerArray;//得到全部graphicLayer数组
            	//纳入裁剪范畴的要素图层的id有
            	var editableLayerIds=["JCFFL3","JCHFL3","JCUFL3","JHGD","LYD","ZPG","WKF","GYTD","JTYD","KG","TG"];
            	var auturalEditLayersId=[];
            	dojo.forEach(graphiclayersArray,function(graphiclayerId){
            		if($.inArray(graphiclayerId,editableLayerIds)!=-1){
            			auturalEditLayersId.push(graphiclayerId)}})
            	debugger;
            	var map=this.map;
            	var graphicnNow=evt.graphic;
            	var geometryNow=evt.graphic.geometry;
        		var query=new Tquery();//query对象
    		    query.geometry=geometryNow;//将来你的区的geometry 
        		this.geometryService=new GeometryService(mapinfoTemplate.geometryServiceUrl);
        		dojo.forEach(auturalEditLayersId,lang.hitch(this,function(layerId){
        		    var xlayer=map.getLayer(layerId);
        		    debugger
        		    xlayer.selectFeatures(query,FeatureLayer.SELECTION_NEW,lang.hitch(this,function(results){//result就是你区域里的所有站点
        		    	if(results.length!=0){
        		    		dojo.forEach(results,lang.hitch(this,function(result){
        		    			if(geometryEngine.contains(result.geometry, query.geometry)||geometryEngine.contains(query.geometry,result.geometry)){
        		    				result.geometry=query.geometry;
        		    				console.log("完全包含或被包含了");
        		    				xlayer.applyEdits(null, [result], null, function(){layer.close(index);layer.msg("更新边界成功!",{icon:1,time:1000})},function(){layer.close(index);layer.msg("更新边界失败!",{icon:2,time:1000})});
        		    			}else{
        		    				this.geometryService.union([result.geometry,query.geometry],function(uni){
        		            			var diff=geometryEngine.difference(uni,query.geometry);
        		        				result.geometry=diff;
        		        				console.log("与若干地块相交了");
        		        				xlayer.applyEdits(null, [result], null, lang.hitch(this,function(){
        		        					layer.close(index);
        		        					layer.msg("更新边界成功!",{icon:1,time:1000})}),
        		        					function(){layer.close(index);
        		        					layer.msg("更新边界失败!",{icon:2,time:1000})});
        		            		}, function(){layer.close(index);
        		            		layer.msg("更新边界失败!",{icon:2,time:1000})});
        		    				var index=layer.load(1);
        		    				debugger
        		    				xlayer.refresh();
        		    			}
        		    		}));
        		    	};
        		    }));
        		}))
            		/* }else{
            		return;
            	  };*/
            },
            DeactiveEditbar:function(){
            	this.editToolbar.deactivate();
            	try{
            	dojo.style(dojo.query(".esriPopupVisible")[0],"display","block")
            	}catch(e){
            		console.log("pop in null");
            	}
            },
            destroy:function(){
    			this.inherited(arguments);
    			this.map = null;
    		},
            geoEdit:function(){
            	if(dojo.query(".esriPopupVisible")[0]){
            		dojo.style(dojo.query(".esriPopupVisible")[0],"display","none")
            	}
				var tool = 0;
				tool = tool | Edit.EDIT_VERTICES; 
				var options = {
						allowAddVertices: true,
						allowDeleteVertices: true,
						uniformScaling: true
				};
				this.editToolbar.activate(tool, this.landgeo, options);	

            },
            getThisLayer:function(){
            	this.LandFeatureLayer=new FeatureLayer(mapinfoTemplate.LandFeatureLayerEdit.layerurl);
            },
            
            bindArgs:function(args){
            	debugger;
            	var attr=args.attributes;
            	$("input[name='projecttype'][value='"+attr["TYPE"]+"']").attr("checked","checked");
            	dojo.query("#LANDBH")[0].value=attr["LANDBH"];
            	dojo.query("#LANDNAME")[0].value=attr["LANDNAME"];
            	dojo.query("#CITY")[0].value=attr["CITY"];
            	dojo.query("#DISTRICT")[0].value=attr["DISTRICT"];
            	dojo.query("#ZHENJIE")[0].value=attr["ZHENJIE"];
            	dojo.query("#EXPENDTYPE")[0].value=attr["EXPENDTYPE"];
            	dojo.query("#ADDRESS")[0].value=attr["ADDRESS"];
            	dojo.query("#PROJECTTYPE")[0].value=attr["PROJECTTYPE"];
            	dojo.query("#XZJSXX")[0].value=attr["XZJSXX"];
            	dojo.query("#TGXX")[0].value=attr["TGXX"];
            	dojo.query("#KGXX")[0].value=attr["KGXX"];
            	dojo.query("#OWNERSHIP")[0].value=attr["OWNERSHIP"];
            	dojo.query("#KGXX")[0].value=attr["KGXX"];
            	dojo.query("#COMPANY")[0].value=attr["COMPANY"];
            	dojo.query("#LICENCE")[0].value=attr["LICENCE"];
            	dojo.query("#QSR")[0].value=attr["QSR"];
            	dojo.query("#LICENCE")[0].value=attr["LICENCE"];
            	dojo.query("#TELL")[0].value=attr["TELL"];
            	dojo.query("#QSRNAME")[0].value=attr["QSRNAME"];
            	dojo.query("#VOLUMERATIO")[0].value=attr["VOLUMERATIO"];
            	dojo.query("#BZJ")[0].value=attr["BZJ"];
            	dojo.query("#LANDVALUE")[0].value=attr["LANDVALUE"];
            	dojo.query("#REGISTERUSER")[0].value=attr["REGISTERUSER"];
            },
            getIndexFromSelectListByVaue:function(selectId,checkValue){
            	var select = dojo.byId(selectId);  
                for(var i=0; i<select.options.length; i++){  
                    if(select.options[i].innerHTML == checkValue){  
                        select.options[i].selected = true;  
                        break;  
                    }  
                } 
                return;
            },
            closeDialog:function(){
            	topic.publish("LandExpandEditWidgetDestroy");	
    			this.inherited("closeDialog",arguments);
    			this.LandFeatureLayer.redraw();
    			this.DeactiveEditbar();
    			this.destroy();
    			dojo.forEach(this.handles,function(handle){
    				handle.remove();
    			})
    		},
    		changeProhectTypeAfterBind:function(args){
    			var isshow = false;
    			var bindProjectType=args.attributes.TYPE;
    			if(this.bindProjectType=="核查项目"){
    				isshow = true;
    			}else if(this.bindProjectType=="洽谈项目"){
    				isshow = false;
    				dojo.byId("YJQYSJ_DESC").innerHTML = "预计签约：";
    				dojo.byId("SJQYSJ_DESC").innerHTML = "预计获取：";
    			}else{
    				isshow = false;
    				dojo.byId("YJQYSJ_DESC").innerHTML = "实际签约：";
    				dojo.byId("SJQYSJ_DESC").innerHTML = "实际获取：";
    			}
    			dojo.toggleClass(dojo.byId("QYSJ"),"unshowed",isshow);
    		},
    		changeProjectTypeHandler:function(item){
    			var selectitem = item.currentTarget;
    			this.projectType = selectitem.attributes["value"].value;
    			var isshow = false;
    			if(this.projectType=="核查项目"){
    				isshow = true;
    			}else if(this.projectType=="洽谈项目"){
    				isshow = false;
    				dojo.byId("YJQYSJ_DESC").innerHTML = "预计签约：";
    				dojo.byId("SJQYSJ_DESC").innerHTML = "预计获取：";
    			}else{
    				isshow = false;
    				dojo.byId("YJQYSJ_DESC").innerHTML = "实际签约：";
    				dojo.byId("SJQYSJ_DESC").innerHTML = "实际获取：";
    			}
    			dojo.toggleClass(dojo.byId("QYSJ"),"unshowed",isshow);
    				
    		},
            saveLandGeometryToDB:function(){
            	var validFields={
					VOLUMERATIO:dojo.query("#VOLUMERATIO")[0],
					BZJ:dojo.query("#BZJ")[0],          
					LANDVALUE:dojo.query("#LANDVALUE")[0]
            	}
            	var reg=new RegExp("^[0-9]+\.{0,1}[0-9]{0,2}$");
            	var count=0
            	for(var i in validFields){
            		if(reg.exec(validFields[i].value)==null){
            			if(count++ == 0){
            				validFields[i].focus();
            			}
            			style.set(validFields[i],"border-color","red");
   
            		}else{
            			if(style.get(validFields[i],"border-color") == "rgb(255, 0, 0)"){
            				style.set(validFields[i],"border-color","");
            			}
            		}
            	}
            	if(count!=0){
            		return false;
            	}
				this.landgeo.attributes={
						XH:dojo.query("#XH")[0].value,           
						TYPE:this.projectType,         
						LANDBH:dojo.query("#LANDBH")[0].value,       
						LANDNAME:dojo.query("#LANDNAME")[0].value,     
						CITY:dojo.query("#CITY")[0].value,         
						DISTRICT:dojo.query("#DISTRICT")[0].value,     
						ZHENJIE:dojo.query("#ZHENJIE")[0].value,      
						ADDRESS:dojo.query("#ADDRESS")[0].value,      
						PROJECTTYPE:dojo.query("#PROJECTTYPE")[0].value,  
						EXPENDTYPE:dojo.query("#EXPENDTYPE")[0].value,   
						TGXX:dojo.query("#TGXX")[0].value,         
						KGXX:dojo.query("#KGXX")[0].value,         
						XZJSXX:dojo.query("#XZJSXX")[0].value,
						OBJECTID:this.landgeo.attributes["OBJECTID"],
						TOTALAREA:dojo.query("#TOTALAREA")[0].value,    
						NETLANDAREA:dojo.query("#NETLANDAREA")[0].value,  
						VOLUMERATIO:dojo.query("#VOLUMERATIO")[0].value, 
						OWNERSHIP:dojo.query("#OWNERSHIP")[0].value,    
						COMPANY:dojo.query("#COMPANY")[0].value,      
						LICENCE:dojo.query("#LICENCE")[0].value,      
						QSR:dojo.query("#QSR")[0].value,          
						QSRNAME:dojo.query("#QSRNAME")[0].value,      
						TELL:dojo.query("#TELL")[0].value,         
						BZJ:dojo.query("#BZJ")[0].value,          
						LANDVALUE:dojo.query("#LANDVALUE")[0].value,    
						REGISTERDATE:dojo.query("#REGISTERDATE")[0].value, 
						REGISTERUSER:ioc.map.userInfoData.USERNAME,						
						YJQYSJ:dojo.query("#YJQYSJ")[0].value,       
						SJQYSJ:dojo.query("#SJQYSJ")[0].value,     
						BZ:dojo.query("#BZ")[0].value 
				};
				console.log(this.landgeo.attributes);
				var self=this;
				this.LandFeatureLayer.applyEdits(null,[this.landgeo],null,
						function(evt){layer.close(index); layer.msg("更新成功!",{icon:1});self.closeDialog()},
						function(evt){layer.close(index); layer.msg("更新失败!",{icon:2})});
				var index=layer.load(1);
            },
    });
});

